package com.ramos.kuaixiao.network;

import android.os.AsyncTask;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.db.AllCustomerDB;
import com.ramos.kuaixiao.db.CustomerDB;
import com.ramos.kuaixiao.db.SaleCustomerDB;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.entity.SaleCustomer;
import com.ramos.kuaixiao.utils.CommUtil;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;

import org.apache.http.Header;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;

public class UpdateCustomerTask extends AsyncTask<Void, Integer, Boolean> {
    private final static String TAG = "UpdateCustomer";

    public UpdateCustomerTask() {
    }

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            getAllCustomer();
        } catch (Exception e) {
            App.isCustomerUpdating = false;
            e.printStackTrace();
        }
        return true;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {

    }

    @Override
    protected void onPostExecute(Boolean result) {

    }

    private void getAllCustomer() {
        try {
            App.isCustomerUpdating = true;
            String url = NetUtils.UPDATE_CUSTOMER;
            long time = new AllCustomerDB().getMaxModifyTime();
            Log.d(TAG, "time :" + time);
            //String path = url + "{\"startModifyTime\":" + time + "}";
            String entity = "{\"startModifyTime\":" + time + "}";
            String path = url + URLEncoder.encode(entity, "UTF-8");
            Log.d(TAG, "path :" + path);
            SyncHttpClient client = new SyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(120000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        //CommUtil.d(App.mContext, TAG, "UpdateCustomer:result=" + result);
                        JSONObject jsonObejct = JSONObject.parseObject(result);
                        if (jsonObejct.getInteger("status") == 200) {
                            JSONObject data = jsonObejct.getJSONObject("data");
                            StringBuilder stringBuilder = new StringBuilder();
                            stringBuilder.append(data.getJSONArray("rows").toString());
                            final int total = data.getIntValue("total");
                            final List<Customer> customerList = JSONArray.parseArray(stringBuilder.toString(), Customer.class);
                            if (customerList != null && customerList.size() > 0) {
                                CommUtil.d(App.mContext, TAG, "List.size()=" + customerList.size());
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        AllCustomerDB customerDB = new AllCustomerDB();
                                        if (customerDB.updateAllCustomer(customerList) == 0) {
                                            if(total > App.PAGE_NUM){
                                                UpdateCustomerTask product4 = new UpdateCustomerTask();
                                                product4.executeOnExecutor(Executors.newCachedThreadPool());
                                            } else {
                                                initCustomer();
                                            }
                                        } else {
                                            App.isCustomerUpdating = false;
                                        }
                                    }
                                }).start();

                            } else {
                                App.isCustomerUpdating = false;
                            }
                        } else{
                            App.isCustomerUpdating = false;
                        }
                    } catch (Exception e) {
                        App.isCustomerUpdating = false;
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                    App.isCustomerUpdating = false;
                }
            });
        } catch (Exception e) {
            App.isCustomerUpdating = false;
            e.printStackTrace();
        }
    }

    private void initCustomer() {
        Set<String> customers = new HashSet<>();
        List<SaleCustomer> list1 = new ArrayList<>();
        list1.addAll(new SaleCustomerDB().findAllCustomer());
        CommUtil.d(App.mContext,TAG, "tbl_SaleCustomer:" + list1.size());
        for (SaleCustomer sale : list1) {
            if (sale.getSaleId().equals(SharedPreference.getPreferString("id"))) {
                customers.add(sale.getCustomerId());
            }
        }
        List<Customer> tmplist = new ArrayList<>();
        List<Customer> list = new ArrayList<>();
        list.addAll(new AllCustomerDB().findAllCustomer());
        CommUtil.d(App.mContext,TAG, "tbl_Customer:" + list.size());
        CommUtil.d(App.mContext,TAG, "tbl_customers:" + customers.size());
        if (customers != null && customers.size() > 0) {
            for (Customer customer : list) {
                //
                for (String s : customers) {
                    if (customer.getId().equals(s)) {
                        tmplist.add(customer);
                    }
                }
            }
            CommUtil.d(App.mContext,TAG, "tbl_Customer1:" + tmplist.size());
            for(Customer customer :  tmplist){
                CommUtil.d(App.mContext,TAG, "initCustomer:" + customer.getQid() + ","+customer.getTelephone());
            }
            CustomerDB customerDB1 = new CustomerDB();
            customerDB1.updateAllCustomer(tmplist);
            App.mCustomerList.clear();
            App.mCustomerList.addAll(tmplist);
            App.isCustomerUpdating = false;
           /* Looper.prepare();
            ToastUtils.show("客户数据已加载完成，总共"+tmplist.size()+"条数据");
            Looper.loop();*/
        } else {
            App.isCustomerUpdating = false;
            /*Looper.prepare();
            ToastUtils.show("未发现客户数据！");
            Looper.loop();*/
        }
    }
}
